/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.TX;

import entity.tx.Advertisement;
import entity.tx.AdvertisementStatistics;
import entity.establishment.Stakeholder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author v-chust
 */
@Stateless
@LocalBean
public class AdvertisementSB implements AdvertisementSBRemote {

    @PersistenceContext()
    EntityManager em;
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

//    @Override
//    public Collection<Advertisement> getRandomThreeAdvertisement() {
//        ArrayList<Advertisement> advertColl = new ArrayList();
//        Collection<Advertisement> returnAdvertColl = new ArrayList();
//        try {
//            Date now = new Date();
//            Query q = em.createQuery("select a from Advertisement a where a.isActivated=true");
//            for (Object o : q.getResultList()) {
//
//                Advertisement a = (Advertisement) o;
//                if (now.after(a.getStartDate()) && now.before(a.getEndDate())) {
//                    advertColl.add(a);
//                }
//            }
//            Random ran = new Random();
//            int numberOfTimes = 3;
//            while (numberOfTimes != 0 && !advertColl.isEmpty()) {
//                int randomnumber = ran.nextInt(advertColl.size());
//                Advertisement tempAdvert = advertColl.get(randomnumber);
//                advertColl.remove(randomnumber);
//
//                if (tempAdvert.isIsSubscription()) {
//
//                    if (!tempAdvert.getLink().startsWith("http://") && !tempAdvert.getLink().trim().equals("")) {
//                        tempAdvert.setLink("http://" + tempAdvert.getLink());
//                    }
//
//                    returnAdvertColl.add(tempAdvert);
//                    recordImpression(tempAdvert);
//                    numberOfTimes--;
//
//                } else if (tempAdvert.isIsImpression()) {
//                    if (tempAdvert.getAdvertisementStatistics() == null || tempAdvert.getAdvertisementStatistics().isEmpty()) {
//
//
//                        if (!tempAdvert.getLink().startsWith("http://") && !tempAdvert.getLink().trim().equals("")) {
//                            tempAdvert.setLink("http://" + tempAdvert.getLink());
//                        }
//
//                        returnAdvertColl.add(tempAdvert);
//                        recordNewImpression(tempAdvert);
//                        numberOfTimes--;
//                    } else {
//                        Iterator k = tempAdvert.getAdvertisementStatistics().iterator();
//                        if (k != null) {
//                            boolean isSuccess = false;
//                            while (k.hasNext()) {
//                                AdvertisementStatistics stats = (AdvertisementStatistics) k.next();
//                                int maxImpression = (int) (tempAdvert.getMaxDailyImpressionAmount() / tempAdvert.getBiddingPrice());
//                                if (now.after(stats.getStartDate()) && now.before(stats.getEndDate())) {
//
//
//                                    if (!tempAdvert.getLink().startsWith("http://") && !tempAdvert.getLink().trim().equals("")) {
//                                        tempAdvert.setLink("http://" + tempAdvert.getLink());
//                                    }
//                                    if (stats.getNoOfImpressions() <= maxImpression) {
//                                        returnAdvertColl.add(tempAdvert);
//                                        recordImpression(tempAdvert);
//                                        numberOfTimes--;
//                                        isSuccess = true;
//                                        break;
//                                    }
//                                }
//                            }
//                            if (!isSuccess) {
//                                //dreamtcs do somethign
//                                returnAdvertColl.add(tempAdvert);
//                                createNewandRecordImpression(tempAdvert);
//                                numberOfTimes--;
//                            }
//                        }// end iterator
//                    }
//                    //check if impression exceeded
//                } else if (tempAdvert.isIsClick()) {
//                    //check if is click exceeded
//                    if (tempAdvert.getAdvertisementStatistics() == null || tempAdvert.getAdvertisementStatistics().isEmpty()) {
//
//
//                        if (!tempAdvert.getLink().startsWith("http://") && !tempAdvert.getLink().trim().equals("")) {
//                            tempAdvert.setLink("http://" + tempAdvert.getLink());
//                        }
//
//                        returnAdvertColl.add(tempAdvert);
//                        recordImpression(tempAdvert);
//                        numberOfTimes--;
//                    } else {
//
//
//                        Iterator k = tempAdvert.getAdvertisementStatistics().iterator();
//                        if (k != null) {
//                            boolean isSuccess = false;
//                            while (k.hasNext()) {
//                                AdvertisementStatistics stats = (AdvertisementStatistics) k.next();
//                                int maxClick = (int) (tempAdvert.getMaxDailyClicksAmount() / tempAdvert.getCostPerClick());
//                                if (now.after(stats.getStartDate()) && now.before(stats.getEndDate())) {
//
//                                    if (!tempAdvert.getLink().startsWith("http://") && !tempAdvert.getLink().trim().equals("")) {
//                                        tempAdvert.setLink("http://" + tempAdvert.getLink());
//                                    }
//                                    if (stats.getNoOfClicks() <= maxClick) {
//                                        returnAdvertColl.add(tempAdvert);
//                                        recordImpression(tempAdvert);
//                                        numberOfTimes--;
//                                        isSuccess = true;
//                                        break;
//                                    }
//                                }
//                            }
//                            if (!isSuccess) {
//                                //dreamtcs do somethign
//                                returnAdvertColl.add(tempAdvert);
//                                createNewandRecordImpression(tempAdvert);
//                                numberOfTimes--;
//                            }
//                        }// end iterator
//                    }
//                }
//            }
//
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return null;
//        }
//
//        return returnAdvertColl;
//    }
//
//    private void createNewandRecordImpression(Advertisement tempAdvert) {
//
//        if (tempAdvert.getTotalImpression() != null) {
//            tempAdvert.setTotalImpression(tempAdvert.getTotalImpression() + 1);
//        }
//
//
//
//        AdvertisementStatistics newMonthstats = new AdvertisementStatistics();
//        newMonthstats.setNoOfImpressions(1);
//        newMonthstats.setNoOfClicks(0);
//        Date today = new Date();
//
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(today);
//
//        calendar.set(Calendar.HOUR, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//        Date firstDayOfMonth = calendar.getTime();
//        newMonthstats.setStartDate(firstDayOfMonth);
//
//
//        calendar.set(Calendar.HOUR, 23);
//        calendar.set(Calendar.MINUTE, 59);
//        calendar.set(Calendar.MILLISECOND, 999);
//        Date lastDayOfMonth = calendar.getTime();
//        newMonthstats.setEndDate(lastDayOfMonth);
//        em.persist(newMonthstats);
//
//        tempAdvert.getAdvertisementStatistics().add(newMonthstats);
//
//    }
//
//    private void recordNewImpression(Advertisement tempAdvert) {
//        if (tempAdvert.getTotalImpression() != null) {
//            tempAdvert.setTotalImpression(tempAdvert.getTotalImpression() + 1);
//        }
//
//        if (tempAdvert.getAdvertisementStatistics() == null || tempAdvert.getAdvertisementStatistics().isEmpty()) {
//
//            AdvertisementStatistics newMonthstats = new AdvertisementStatistics();
//            newMonthstats.setNoOfImpressions(1);
//            newMonthstats.setNoOfClicks(0);
//            Date today = new Date();
//
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(today);
//
//            calendar.set(Calendar.HOUR, 0);
//            calendar.set(Calendar.MINUTE, 0);
//            calendar.set(Calendar.MILLISECOND, 0);
//            Date firstDayOfMonth = calendar.getTime();
//            newMonthstats.setStartDate(firstDayOfMonth);
//
//
//            calendar.set(Calendar.HOUR, 23);
//            calendar.set(Calendar.MINUTE, 59);
//            calendar.set(Calendar.MILLISECOND, 999);
//            Date lastDayOfMonth = calendar.getTime();
//            newMonthstats.setEndDate(lastDayOfMonth);
//            em.persist(newMonthstats);
//
//            List<AdvertisementStatistics> adStatColl = new ArrayList();
//            adStatColl.add(newMonthstats);
//            tempAdvert.setAdvertisementStatistics(adStatColl);
//
//        }
//    }
//
//    private void recordImpression(Advertisement tempAdvert) {
//
//        if (tempAdvert.getTotalImpression() != null) {
//            tempAdvert.setTotalImpression(tempAdvert.getTotalImpression() + 1);
//        }
//        //if is first time
//
//        boolean isNewDay = true;
//        Iterator l = tempAdvert.getAdvertisementStatistics().iterator();
//        if (l != null) {
//            while (l.hasNext()) {
//                AdvertisementStatistics stats2 = (AdvertisementStatistics) l.next();
//                Date now2 = new Date();
//                if (now2.after(stats2.getStartDate()) && now2.before(stats2.getEndDate())) {
//                    stats2.setNoOfImpressions(stats2.getNoOfImpressions() + 1);
//                    em.persist(stats2);
//                    isNewDay = false;
//                    break;
//                }
//            }
//            if (isNewDay) {
//                AdvertisementStatistics newMonthstats = new AdvertisementStatistics();
//                newMonthstats.setNoOfImpressions(1);
//                newMonthstats.setNoOfClicks(0);
//                Date today = new Date();
//
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(today);
//
//                calendar.set(Calendar.HOUR, 0);
//                calendar.set(Calendar.MINUTE, 0);
//                calendar.set(Calendar.MILLISECOND, 0);
//                Date firstDayOfMonth = calendar.getTime();
//                newMonthstats.setStartDate(firstDayOfMonth);
//
//                calendar.set(Calendar.HOUR, 23);
//                calendar.set(Calendar.MINUTE, 59);
//                calendar.set(Calendar.MILLISECOND, 999);
//                Date lastDayOfMonth = calendar.getTime();
//                newMonthstats.setEndDate(lastDayOfMonth);
//                em.persist(newMonthstats);
//                tempAdvert.getAdvertisementStatistics().add(newMonthstats);
//
//            }//end if new month
//        }// end iterator
//
//    }
//
//    @Override
//    public void recordAdvertisementClick(Long accountId, Long advertId, String source, String destination, Date now) {
//        try {
//            Account userAcc = null;
//            try {
//                userAcc = em.find(Account.class, accountId);
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
//            Advertisement advert = null;
//            try {
//                advert = em.find(Advertisement.class, advertId);
//                if (advert.getTotalClicks() != null) {
//                    advert.setTotalClicks(advert.getTotalClicks() + 1);
//                }
//
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
//            if (advert != null) {
//                AdsTrack adstrack = new AdsTrack();
//                adstrack.setAcc(userAcc);
//                adstrack.setClickFrom(source);
//                adstrack.setAd(advert);
//                adstrack.setVisitTime(now.getTime() / 1000);
//                em.persist(adstrack);
//
//                if (advert.getAdvertisementStatistics() != null) {
//                    Iterator i = advert.getAdvertisementStatistics().iterator();
//                    if (i.hasNext()) {
//                        boolean isSuccess = false;
//                        while (i.hasNext()) {
//                            AdvertisementStatistics stats = (AdvertisementStatistics) i.next();
//
//                            if (now.after(stats.getStartDate()) && now.before(stats.getEndDate())) {
//                                stats.setNoOfClicks(stats.getNoOfClicks() + 1);
//                                isSuccess = true;
//                                break;
//                            }
//                        }
//                        if (isSuccess == false) {
//
//                            AdvertisementStatistics newMonthstats = new AdvertisementStatistics();
//                            newMonthstats.setNoOfImpressions(0);
//                            newMonthstats.setNoOfClicks(1);
//                            Date today = new Date();
//
//                            Calendar calendar = Calendar.getInstance();
//                            calendar.setTime(today);
//
//                            calendar.set(Calendar.HOUR, 0);
//                            calendar.set(Calendar.MINUTE, 0);
//                            calendar.set(Calendar.MILLISECOND, 0);
//                            Date firstDayOfMonth = calendar.getTime();
//                            newMonthstats.setStartDate(firstDayOfMonth);
//
//
//                            calendar.set(Calendar.HOUR, 23);
//                            calendar.set(Calendar.MINUTE, 59);
//                            calendar.set(Calendar.MILLISECOND, 999);
//                            Date lastDayOfMonth = calendar.getTime();
//                            newMonthstats.setEndDate(lastDayOfMonth);
//                            em.persist(newMonthstats);
//
//                            advert.getAdvertisementStatistics().add(newMonthstats);
//                        }
//                    }
//
//                }
//            }
//
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//    }

    //@Override
    public boolean addAdvertisement(String title,
            String tags,
            String filePath,
            String description,
            String link,
            boolean isSubscription,
            boolean isImpression,
            boolean isClick,
            Double biddingPrice,
            boolean isActivated,
            Double maxClicks,
            Double maxImpression, String stakeholderName, Date startDate, Date endDate) {
        boolean isActive;
        
        if(!isClick && !isImpression)
            isActive=false;
        else
            isActive = true;
        
      
        
        Calendar start = Calendar.getInstance();
        start.set(Calendar.HOUR, 0);
        start.set(Calendar.MINUTE, 0);

        Calendar end = Calendar.getInstance();
        end.set(Calendar.HOUR, 23);
        end.set(Calendar.MINUTE, 59);

        Date statisticStartDate = start.getTime();
        Date statisticEndDate = end.getTime();

        Query q = em.createQuery("SELECT c FROM Stakeholder c WHERE c.name = :paramName");
        q.setParameter("paramName", stakeholderName);
        List resultList = q.getResultList();
        if (resultList.isEmpty()) {
            return false;
        }
        if (isImpression == false) {
            biddingPrice = 0.0;
        }

        Stakeholder stakeholder = (Stakeholder) resultList.get(0);
        Advertisement ads = new Advertisement();
        AdvertisementStatistics adstats = new AdvertisementStatistics();
        List<AdvertisementStatistics> adstatsList = new ArrayList<AdvertisementStatistics>();
        List<Advertisement> adsList = new ArrayList<Advertisement>();
        
        
        
        if (stakeholder != null) {
            adsList = stakeholder.getAdvertisement();
            Double costPerClick = stakeholder.getStakeholderTier().getCostPerClick();
            ads.setTitle(title);
            ads.setTags(tags);
            ads.setFilePath(filePath);
            ads.setDescription(description);
            ads.setLink(link);
            ads.setIsSubscription(true);
            ads.setIsImpression(isImpression);
            ads.setIsClick(isClick);
            ads.setBiddingPrice(biddingPrice);
            ads.setIsActivated(isActive);
            ads.setMaxDailyClicksAmount(maxClicks);
            ads.setMaxDailyImpressionAmount(maxImpression);
            ads.setStakeholder(stakeholder);
            ads.setStartDate(startDate);
            ads.setEndDate(endDate);
            ads.setTotalClicks(0);
            ads.setTotalImpression(0);
            ads.setCostPerClick(costPerClick);

            adstats.setStartDate(statisticStartDate);
            adstats.setEndDate(statisticEndDate);
            adstats.setNoOfClicks(0);
            adstats.setNoOfImpressions(0);
            adstats.setIsCompute(false);
            adstats.setDailyCharges(0.0);
            em.persist(adstats);

            adstatsList.add(adstats);
            ads.setAdvertisementStatistics(adstatsList);
            em.persist(ads);


            adsList.add(ads);
            stakeholder.setAdvertisement(adsList);
            em.persist(stakeholder);

            return true;
        }


        return false;
    }
    
    public List<Advertisement> retrieveAds(String name){
        
        Query q = em.createQuery("SELECT c FROM Stakeholder c WHERE c.name = :paramName");
        q.setParameter("paramName", name);
        List resultList = q.getResultList();
        Stakeholder stakeholder = (Stakeholder) resultList.get(0);
        Long stakeholderId = stakeholder.getId();
        
        Query q2 = em.createQuery("SELECT c FROM Advertisement c WHERE c.stakeholder.id = :paramName AND c.isActivated = :paramName2");
        q2.setParameter("paramName", stakeholderId);
        q2.setParameter("paramName2", true);
        List resultList2 = q2.getResultList();
        
        List<Advertisement> adList = new ArrayList<Advertisement>();
        
        for (Object o : resultList2){
            Advertisement ad = (Advertisement)o;
            adList.add(ad);
        }
        
        return adList;
    }
    
    public List<Advertisement> retrieveAds2(String name){
        
        System.out.println("CHECKED!!");
        Query q = em.createQuery("SELECT c FROM Stakeholder c WHERE c.name = :paramName");
        q.setParameter("paramName", name);
        List resultList = q.getResultList();
        Stakeholder stakeholder = (Stakeholder) resultList.get(0);
        Long stakeholderId = stakeholder.getId();
        
        Query q2 = em.createQuery("SELECT c FROM Advertisement c WHERE c.stakeholder.id = :paramName AND c.isActivated = :paramName2");
        q2.setParameter("paramName", stakeholderId);
        q2.setParameter("paramName2", true);
        List resultList2 = q2.getResultList();
        
        List<Advertisement> adList = new ArrayList<Advertisement>();
        
        if(resultList2.isEmpty()) {
        return adList;
        }
        
        for (Object o : resultList2){
            Advertisement ad = (Advertisement)o;
            Date today = new Date();
            Calendar cal = Calendar.getInstance();
            today = cal.getTime();
            if(( today.compareTo(ad.getEndDate())) > 0){
                adList.add(ad);
            }
        }  
        return adList;
    }
    
    public void deActivate(long id) {
        Advertisement ad = em.find(Advertisement.class,id);
        ad.setIsActivated(false);
        em.merge(ad);
    }

  
}
